<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :collapse="false" :isSubmitBtn="false"></TopFilter>

    <FilterTable
      ref="questionTable"
      height="auto"
      :columns="columns"
      columnsRef="questioncolumsTable"
      selectionType="single"
      :datakey="'rows'"
      :fetchapi="questionFetchApi"
      :params="fetchQuestionParams"
      :isPagination="true"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
      :onSyncTableData="getQuestionAll"
    >
      <!-- <template slot="controls">
        <el-button size="small" type="primary" @click="editQuestion">编辑</el-button>
      </template>-->
    </FilterTable>

    <div class="vehicle-details-wrap">
      <div class="box">
        <FormPanel ref="trackFormPanel" :list="feesSettlementList" :cols="1" :labelWidth="100" :isSubmitBtn="false" />
      </div>
    </div>
    <div style="marginBottom:10px">
      <p>跟踪记录</p>
    </div>
    <FilterTable
      ref="trackTable"
      height="auto"
      columnsRef="lxjczclglinvoiceRegisterTable"
      :columns="trackColumns"
      :datakey="'rows'"
      :fetchapi="fetchTrackApi"
      :params="fetchTrackParams"
      selectionType="single"
      :isColumnFilter="false"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectTrackColumns = columns)"
      :onSyncTableData="getAll"
    >
      <template slot="controls">
        <el-button size="mini" type="primary" @click="addTrack">新增</el-button>
        <el-button v-show="trackList.length !== 0" size="mini" type="primary" @click="deleteTrackRecord">删除</el-button>
      </template>
    </FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" icon="el-icon-edit" @click="callbackHistory">回访历史</el-button>
      <el-button v-if="this.getdata.TRACE_TAG == 10041002" type="primary" icon="el-icon-tickets" @click="saveDialog">保存</el-button>
      <el-button icon="el-icon-refresh-left" @click="closeDialog">取 消</el-button>
    </div>

    <BaseDialog title="问卷修改" :modal="true" destroyOnClose :visible.sync="showEditQuestion" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto' }">
      <EditQuestionModel :chooseQuestion="chooseQuestion" @closeEdit="closeEditQuestion"></EditQuestionModel>
    </BaseDialog>

    <BaseDialog title="跟踪记录新增" :modal="true" destroyOnClose width="300px" :visible.sync="showTrackRecord" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto' }">
      <AddRecordModel @close="closeTrackRecord" @saveRecord="saveTrackRecord"></AddRecordModel>
    </BaseDialog>
    <!-- 回访历史 -->
    <BaseDialog :visible.sync="returnHis" title="回访信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ReturnHisModel @close="closeReturnHis"></ReturnHisModel>
    </BaseDialog>
  </div>
</template>

<script>
import ReturnHisModel from './returnHisModel';
import AddRecordModel from './question/addRecordModel';
import EditQuestionModel from './question/editQuestionModel';
import { findAllQuestion, questionnaireInfo, queryTaskLog, saveLossReturnVisit } from '@/api/customerRepair/customerLoss/taskEntry';
import { dictionary } from '@/utils/dictMixin';
export default {
  name: 'questionnaireModel',
  components: {
    AddRecordModel,
    ReturnHisModel,
    EditQuestionModel
  },
  mixins: [dictionary],
  props: ['getdata'],
  data() {
    this.isDisabled = true;
    this.table = null;
    return {
      topFilterList: this.createTopFilterList(),
      isDisabled: true,
      selectColumns: [],
      columns: this.createTableColumns(),
      questionFetchApi: questionnaireInfo,
      fetchQuestionParams: { xhrAbort: true },
      showEditQuestion: false,
      chooseQuestion: null,
      questionList: [],
      feesSettlementList: this.createFeesSettlementList(),
      trackColumns: this.createTableColumnsTrack(),
      selectTrackColumns: [], // 选中的值
      fetchTrackApi: queryTaskLog, // 跟踪记录
      fetchTrackParams: { xhrAbort: true },
      showTrackRecord: false, // 是否显示跟踪记录新增
      trackList: [], // 跟踪记录数据
      returnHis: false // 是否显示回访信息
    };
  },
  mounted() {
    this.table = this.$refs.trackTable.$refs.pageTable;
    this.queryQuestionSelectOptions();
    this.queryQuestionInfoFun(); // 问卷数据
    this.queryTrackFun(); // 跟踪记录
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '问卷选择',
          fieldName: 'Questionaire',
          palceholder: '请选择',
          itemList: [],
          disabled: this.getdata.TRACE_TAG == 10041001 ? true : false,
          change: val => {
            this.queryQuestionInfoFun(val);
          }
        },
        {
          type: 'INPUT',
          label: '跟踪员',
          fieldName: 'trancer',
          initialValue: this.getdata.EMPLOYEE_NAME,
          disabled: this.isDisabled
        },
        {
          type: 'DATE',
          label: '跟踪时间',
          fieldName: 'INPUT_DATE',
          initialValue: this.getdata.INPUT_DATE,
          disabled: this.isDisabled,
          valueFormat: 'yyyy-MM-dd'
        }
      ];
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'OPERATION',
          width: 80,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editQuestion(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '问卷',
          dataIndex: 'QUESTIONNAIRE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '问题名称',
          dataIndex: 'QUESTION_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '问题内容',
          dataIndex: 'QUESTION_CONTENT',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '类型',
          dataIndex: 'QUESTION_TYPE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '必填',
          dataIndex: 'IS_MUST_FILLED',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '答案',
          dataIndex: 'ANSWER',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },

    createTableColumnsTrack() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '跟踪时间',
          dataIndex: 'TRACE_LOG_DATE0',
          sorter: true
        },
        {
          title: '描述',
          dataIndex: 'TRACE_LOG_DESC0',
          sorter: true,
          render: props => {
            return <el-input v-model={props.row.TRACE_LOG_DESC0}></el-input>;
          }
        }
      ];
    },
    // 跟踪状态form
    createFeesSettlementList() {
      return [
        {
          type: 'SELECT',
          label: '跟踪状态',
          fieldName: 'traceStatus',
          placeholder: '请选择',
          disabled: this.getdata.TRACE_TAG == 10041001 ? true : false,
          itemList: this.createDictList('8058')
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入',
          disabled: this.getdata.TRACE_TAG == 10041001 ? true : false
        }
      ];
    },
    // 获取问卷选择下拉框数据
    async queryQuestionSelectOptions() {
      const res = await findAllQuestion();
      let selectOptions = [];
      res.data.map(x => selectOptions.push({ text: x.QUESTIONNAIRE_NAME, value: x.QUESTIONNAIRE_CODE }));

      this.topFilterList.map(x => {
        if (x.fieldName === 'Questionaire') {
          x.itemList = selectOptions;
        }
        return;
      });
    },
    // 查询问卷数据
    queryQuestionInfoFun(val) {
      let newObj = {
        Questionaire: val,
        traceItemId: this.getdata.ITEM_ID
      };
      this.fetchQuestionParams = Object.assign({}, newObj, { xhrAbort: false });
    },

    // 显示编辑问题
    editQuestion(val) {
      this.chooseQuestion = val;
      this.showEditQuestion = true;
    },
    // 取消编辑问题
    closeEditQuestion(val) {
      this.showEditQuestion = false;
    },
    // 获得问题数据
    getQuestionAll(val) {
      this.questionList = val;
    },
    // 查询跟踪记录
    queryTrackFun() {
      let newObj = {
        VIN: this.getdata.VIN,
        OWNER_NO: this.getdata.OWNER_NO,
        TRACE_ITEM_ID: this.getdata.ITEM_ID,
        TRANCER: this.getdata.TRANCER
      };
      this.fetchTrackParams = Object.assign({}, newObj, { xhrAbort: false });
    },
    // 显示跟踪记录新增
    addTrack() {
      this.showTrackRecord = true;
    },
    // 关闭跟踪记录
    closeTrackRecord() {
      this.showTrackRecord = false;
    },
    // 保存跟踪记录
    saveTrackRecord(obj) {
      this.showTrackRecord = false;
      this.table.EXECUTE_INSERT({ TRACE_LOG_DATE0: obj.traceLogDate, TRACE_LOG_DESC0: obj.traceLogDesc });
    },
    // 删除跟踪记录
    deleteTrackRecord() {
      this.table.EXECUTE_DELETE();
    },
    // 获取跟踪记录数据
    getAll(val) {
      this.trackList = val;
    },
    // 回访历史
    callbackHistory() {
      this.returnHis = true;
    },
    closeReturnHis(val) {
      this.returnHis = val;
    },
    // 保存
    saveDialog() {
      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let Questionaire = this.topFilterList.find(item => item.fieldName === 'Questionaire').initialValue;
          let traceStatus = this.feesSettlementList.find(item => item.fieldName === 'traceStatus').initialValue;
          let remark = this.feesSettlementList.find(item => item.fieldName === 'remark').initialValue;
          let dms_table = this.questionList;
          let dms_tms = [];
          this.trackList.map(x => {
            dms_tms.push({ TRACE_LOG_DATE: x.TRACE_LOG_DATE0, TRACE_LOG_DESC: x.TRACE_LOG_DESC0 });
          });
          let params = {
            Questionaire,
            VIN: this.getdata.VIN,
            OWNER_NO: this.getdata.OWNER_NO,
            TRACE_ITEM_ID: this.getdata.ITEM_ID,
            TRANCER: this.getdata.TRANCER,
            traceStatus,
            remark,
            dms_table,
            dms_tms
          };
          console.log(JSON.stringify(params));
          saveLossReturnVisit(params).then(res => {
            if (res.resultCode === 200) {
              this.$message.success('保存成功');
              this.closeDialog();
            }
          });
        })
        .catch(() => {});
    },
    // 取消
    closeDialog() {
      this.$emit('closeDialog', false);
    }
  }
};
</script>

<style lang="less" scoped>
.vehicle-details-wrap {
  position: relative;
  margin-top: 20px;
  padding-bottom: @modulePadding;
  .box {
    border: 1px solid #ccc;
    padding-top: 15px;
    padding-right: 15px;
    border-radius: @borderRadius;
    margin-bottom: 20px;
    box-shadow: @boxShadow;
  }
}
p {
  background-color: #d3dce6;
  height: 20px;
  line-height: 20px;
  margin-bottom: 10px;
}
</style>
